/*
 * BuilderExpert.h
 *
 *  Created on: Nov 20, 2008
 *      Author: Ryan
 */

#ifndef BUILDEREXPERT_H_
#define BUILDEREXPERT_H_

#include "../../../OOInterface/Objects/Player.h"
#include "../../../OOInterface/Objects/Point3.h"

#include "../../../OOInterface/AIInterface.h"
#include "../../../OOInterface/Interfaces/GameListener.h"

#include "../UnitAnalyzers/FilterVisitor.h"
#include "InfrastructureMap.h"
#include "ResourceReservation.h"

#include <queue>
#include <boost/thread/mutex.hpp>

class BuilderExpert : public OOInterface::GameListener
{
public:
	BuilderExpert( OOInterface::AIInterface* i, OOInterface::ConstPlayerPtr self, ResourceReservation* reserve ):
		_i(i), _self(self), _reservation(reserve), _infrastructure( i->getGameMap() )
	{
		_i->addGameListener( this );
	}
	virtual ~BuilderExpert() {}

	void run();

	virtual void handle( OOInterface::ConstGameEventPtr event );

private:
	OOInterface::AIInterface* _i;
	OOInterface::ConstPlayerPtr _self;
	ResourceReservation* _reservation;

	InfrastructureMap _infrastructure;

	OOInterface::ConstUnitSet _idleBuilders;

	OOInterface::ConstUnitSet _defensiveBuildings;
	OOInterface::ConstUnitSet _factories;
	OOInterface::ConstUnitSet _extractors;
	OOInterface::ConstUnitSet _resourceGenerators;

	typedef std::pair< OOInterface::ConstUnitPtr, OOInterface::Point3f> BuildingPointPair;
	std::queue< BuildingPointPair > _buildQueue;

	std::queue< OOInterface::ConstUnitPtr > _calcBuildQueue;

	void pushOntoQueue( OOInterface::ConstUnitPtr building, OOInterface::Point3f loc );
	void pushOntoQueue( OOInterface::ConstUnitPtr building );

	std::queue< OOInterface::ConstGameEventPtr > _eventQueue;
	boost::mutex _mutex;

	void checkIfResourcesAreNeeded();

	void handleBufferedEvents();

	void distributeBuildingJobs();
	void updateBuilderList();
	void updateList( FilterVisitor& filter, OOInterface::ConstUnitSet& list );

	void giveOrder( OOInterface::ConstUnitPtr builder, OOInterface::ConstCommandPtr command, ResourceMap cost);
};

#endif /* BUILDEREXPERT_H_ */
